package com.zjcode.cdcer.service.impl;

import com.alibaba.fastjson.JSON;
import com.chinatechstar.component.commons.service.BaseService;
import com.chinatechstar.component.commons.supports.PageData;
import com.xxl.job.core.context.XxlJobHelper;
import com.zjcode.cdcer.mapper.*;
import com.zjcode.cdcer.model.CerDataScreen;
import com.zjcode.cdcer.model.Histogram;
import com.zjcode.cdcer.service.CerDataScreenService;
import com.zjcode.cdcer.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class CerDataScreenServiceImpl implements CerDataScreenService, BaseService {

    @Autowired
    private CerDataScreenMapper cerDataScreenMapper;

    @Autowired
    private CerSysteminitImportInfoMapper cerSysteminitImportInfoMapper;

    @Autowired
    private CerSysteminitImportOfficialInfoMapper cerSysteminitImportOfficialInfoMapper;

    @Autowired
    private CerDetaildataImportInfoMapper cerDetaildataImportInfoMapper;

    @Autowired
    private CerDetaildataImportOfficeInfoMapper cerDetaildataImportOfficeInfoMapper;

    @Autowired
    private CerGastroscopeDiagnosisCollectInfoMapper cerGastroscopeDiagnosisCollectInfoMapper;

    @Autowired
    private ZjcodeSysRegionMapper zjcodeSysRegionMapper;

    @Override
    public Map<String, Object> getDataScreen(PageData pageData) {
        //时间对象
        Calendar calendar = Calendar.getInstance();
        // 获取当前年
        String year = String.valueOf(calendar.get(Calendar.YEAR));
        // 获取当前月份
        String month = (String) pageData.get("month");

        //String month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
        // 今天几哈
        //System.out.println(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        ////先删除（物理删除）
        //cerDataScreenMapper.deleteAllByCondition(year, month);
        ////新增返回数据影响行数
        //int result = handleDataScreen(year, month);
        //if (result > 0) {
        //    return cerDataScreenMapper.queryDataScreen(year, month);
        //}
        //return new LinkedHashMap<>();
        //LinkedHashMap<String, Object> list = cerDataScreenMapper.queryDataScreen(year, month);

        // 读取正式数据
        LinkedHashMap<String, Object> list = cerDataScreenMapper.selectAllBy(year, month, "安徽");
        // 测试情况下,读取指定月份的数据
        //LinkedHashMap<String, Object> list = cerDataScreenMapper.selectAllBy(year, "9", "安徽");
        if (CollectionUtils.isEmpty(list)) {
            // 每月无数据时，不应该返回null，故做新增数据操作
            updateDataScreenDB(Integer.parseInt(year), Integer.parseInt(month));
            list = cerDataScreenMapper.selectAllBy(year, month, "安徽");
        }
        return list;
    }

    @Override
    public Map<String, Object> getAreaCancerCount(PageData pageData) {
        Map<String, Object> map = new HashMap<>();
        Object areaName = pageData.get("areaName");
        String month = (String) pageData.get("month");
        if (Objects.nonNull(areaName)) {
            //根据地图板块名获取详情数据正式库三癌数据
            CerDataScreen dataScreen = new CerDataScreen();
            dataScreen.setId(get32UUID());

            // 获取当前月份，开始获取数据
            Date time = Utils.getFirstDay(1);
            List<LinkedHashMap<String, Object>> detailOfficialData = cerDetaildataImportOfficeInfoMapper.detailOfficialData(
                time,
                areaName.toString());

            //详情数据正式库-食管癌分布数量
            long sgaCount = handlePieChart("sgbl_code", detailOfficialData);
            dataScreen.setSga_total((int) sgaCount);

            //详情数据正式库-胃癌分布数量
            long waCount = handlePieChart("wbl_code", detailOfficialData);
            dataScreen.setWa_total((int) waCount);

            //详情数据正式库-贲门癌分布数量
            long bmaCount = handlePieChart("bmbl_code", detailOfficialData);
            dataScreen.setBma_total((int) bmaCount);

            //三癌总数-当前月份的数据
            List<LinkedHashMap<String, Object>> allDetailOfficialData = cerDetaildataImportOfficeInfoMapper.countDetailOfficialData(
                time);
            //三癌总数
            int saTotal =
                (int) handlePieChart("sgbl_code", allDetailOfficialData) + (int) handlePieChart(
                    "wbl_code",
                    allDetailOfficialData) + (int) handlePieChart("bmbl_code",
                                                                  allDetailOfficialData);
            dataScreen.setSa_total(saTotal);

            map.put("dataScreen", dataScreen);

            //按月统计初始数据正式库数据
            List<LinkedHashMap<String, Object>> initOfficialData = cerSysteminitImportOfficialInfoMapper.initOfficialDataByMonth(
                areaName.toString());

            //按月统计详情数据正式库数据
            List<LinkedHashMap<String, Object>> detailOfficialDataByMonth = cerDetaildataImportOfficeInfoMapper.detailOfficialDataByMonth(
                areaName.toString());

            // 处理柱状图数据
            Map<String, Object> hashMap = new HashMap<>();
            List<CerDataScreen> barData1 = handleBarData(initOfficialData, "1");
            hashMap.put("init", barData1);
            List<CerDataScreen> barData2 = handleBarData(detailOfficialDataByMonth, "2");
            hashMap.put("detail", barData2);
            // 需要根据所选择的地市,读取对应的地市的胃镜数据
            List<CerDataScreen> cerDataScreens = cerDataScreenMapper.selectAllByExtFlag(areaName.toString());
            List<CerDataScreen> barData3 = handleBarData4Wj(cerDataScreens);
            hashMap.put("wjcounts", barData3);
            map.put("monthData", hashMap);

            if (StringUtils.isNotEmpty(areaName.toString())) {
                LocalDate now = LocalDate.now();
                //LinkedHashMap<String, Object> basicData = cerDataScreenMapper.selectAllBy(String.valueOf(
                //    now.getYear()), String.valueOf(now.getMonthValue()), areaName.toString());

                // 目前写死为9月份
                //LinkedHashMap<String, Object> basicData = cerDataScreenMapper.selectAllBy(String.valueOf(
                //    now.getYear()), "9", areaName.toString());

                LinkedHashMap<String, Object> basicData = cerDataScreenMapper.selectAllBy(String.valueOf(
                    now.getYear()), month, areaName.toString());

                /// 点击更新地图数据时  本月无数据时，不应该返回null，故做新增数据操作
                if (CollectionUtils.isEmpty(basicData)) {
                    handleDataScreen(String.valueOf(now.getYear()),
                                     String.valueOf(now.getMonthValue()),
                                     areaName.toString());
                    basicData = cerDataScreenMapper.selectAllBy(String.valueOf(now.getYear()),
                                                                String.valueOf(now.getMonthValue()),
                                                                areaName.toString());
                }
                map.put("basicData", basicData);
            } else {
                LocalDate now = LocalDate.now();
                LinkedHashMap<String, Object> basicData = cerDataScreenMapper.selectAllBy(String.valueOf(
                    now.getYear()), String.valueOf(now.getMonthValue()), "安徽");
                map.put("basicData", basicData);
            }

            return map;
        }
        return map;
    }

    /**
     * 按照区域解析出胃镜全年数据列表
     *
     * @param source
     * @return
     */
    private List<CerDataScreen> handleBarData4Wj(List<CerDataScreen> source) {
        int year = LocalDate
            .now()
            .getYear();

        Map<String, Object> map = new HashMap<>();
        map.put("1", year + "01");
        map.put("2", year + "02");
        map.put("3", year + "03");
        map.put("4", year + "04");
        map.put("5", year + "05");
        map.put("6", year + "06");
        map.put("7", year + "07");
        map.put("8", year + "08");
        map.put("9", year + "09");
        map.put("10", year + "10");
        map.put("11", year + "11");
        map.put("12", year + "12");

        // 数据集合
        List<CerDataScreen> screens = new ArrayList<>();
        List<CerDataScreen> result = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            CerDataScreen dataScreen = new CerDataScreen();
            // 主键
            dataScreen.setId(get32UUID());
            int finalI = i;
            Optional<CerDataScreen> first = source
                .stream()
                .filter(each -> each.getMonth() == finalI)
                .findFirst();
            if (first.isPresent()) {
                dataScreen.setExt_flag(map.get(String.valueOf(i)).toString());
                dataScreen.setWjjc_total(first
                                             .get()
                                             .getWjjc_total());
            } else {
                dataScreen.setExt_flag(map.get(String.valueOf(i)).toString());
                dataScreen.setWjjc_total(0);
            }
            result.add(dataScreen);
        }
        return result;
    }

    private List<CerDataScreen> handleBarData(List<LinkedHashMap<String, Object>> data,
                                              String type) {
        int year = LocalDate
            .now()
            .getYear();

        // 数据集合
        List<CerDataScreen> screens = new ArrayList<>();
        //字段map
        Map<String, Object> map = new HashMap<>();
        map.put(year + "01", "0");
        map.put(year + "02", "0");
        map.put(year + "03", "0");
        map.put(year + "04", "0");
        map.put(year + "05", "0");
        map.put(year + "06", "0");
        map.put(year + "07", "0");
        map.put(year + "08", "0");
        map.put(year + "09", "0");
        map.put(year + "10", "0");
        map.put(year + "11", "0");
        map.put(year + "12", "0");

        // 处理数据
        switch (type) {
            case "1":
                //循化匹配数据
                map.forEach((k, v) -> {
                    CerDataScreen dataScreen = new CerDataScreen();
                    // 主键
                    dataScreen.setId(get32UUID());
                    data
                        .stream()
                        .forEach(each -> {
                            String month = each
                                .get("month")
                                .toString();
                            if (k.equals(month)) {
                                // 月份
                                dataScreen.setExt_flag(month);
                                // 初始数据正式库数量
                                dataScreen.setCssjshzsk_total(Integer.valueOf(each
                                                                                  .get("count")
                                                                                  .toString()));
                            }
                        });
                    if (Objects.isNull(dataScreen.getExt_flag())
                        && Objects.isNull(dataScreen.getCssjshzsk_total())) {
                        // 月份
                        dataScreen.setExt_flag(k);
                        // 初始数据正式库数量
                        dataScreen.setCssjshzsk_total(0);
                    }
                    screens.add(dataScreen);
                });
                break;
            case "2":
                //循化匹配数据
                map.forEach((k, v) -> {
                    CerDataScreen dataScreen = new CerDataScreen();
                    // 主键
                    dataScreen.setId(get32UUID());
                    data
                        .stream()
                        .forEach(each -> {
                            String month = each
                                .get("month")
                                .toString();
                            if (k.equals(month)) {
                                // 月份
                                dataScreen.setExt_flag(month);
                                // 详情数据正式库数量
                                dataScreen.setXqsjsbzsk_total(Integer.valueOf(each
                                                                                  .get("count")
                                                                                  .toString()));
                            }
                        });
                    if (Objects.isNull(dataScreen.getExt_flag())
                        && Objects.isNull(dataScreen.getXqsjsbzsk_total())) {
                        // 月份
                        dataScreen.setExt_flag(k);
                        // 详情数据正式库数量
                        dataScreen.setXqsjsbzsk_total(0);
                    }
                    screens.add(dataScreen);
                });
                break;
            default:
                break;
        }
        return screens;
    }

    @Override
    public void updateDataScreenDB(int year, int month) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        String y = String.valueOf(year);
        String m = String.valueOf(month);

        ////先删除（物理删除）
        cerDataScreenMapper.deleteAllByCondition(y, m);
        ////新增返回数据影响行数(全省)
        int result = handleDataScreen(y, m, "安徽省");
        // 维护各地市的数据(各个城市)
        handleDataScreenSub(y, m);
        stopWatch.stop();
        log.info("更新数据屏数据影响行数：{}", result);
        log.info("更新大屏数据屏耗时：{}", stopWatch.getTotalTimeMillis());
    }

    /**
     * 处理组装大屏数据
     */
    private int handleDataScreen(String year, String month, String areaName) {
        //新建数据大屏实体
        CerDataScreen dataScreen = new CerDataScreen();
        //主键
        dataScreen.setId(get32UUID());
        //当前年份
        dataScreen.setYear(Integer.valueOf(year));
        //当前月份
        dataScreen.setMonth(Integer.valueOf(month));

        // 获取当前月份，开始获取数据
        Date time = Utils.getFirstDay(1);

        // 获取安徽省下各个城市,在指定年月情况下的,每月上报胃镜的个数
        Map<String, String> gastroscopeCountMap = getGastroscopeCountMap(year, month);

        //1. 初始数据上报统计人数（不管有没有错误，条件为当前月份）
        int initDataCount = cerSysteminitImportInfoMapper.countInitData(time);
        dataScreen.setCssjsb_total(initDataCount);

        //2. 初始数据正式库统计人数（一定是正确的，条件为当前月份）
        List<LinkedHashMap<String, Object>> initOfficialData = cerSysteminitImportOfficialInfoMapper.initOfficialData(
            time);
        dataScreen.setCssjshzsk_total(initOfficialData.size());

        //3. 详情数据上报统计人数（不管有没有错误的，条件为当前月份）
        int detailDataCount = cerDetaildataImportInfoMapper.countDetailData(time);
        dataScreen.setXqsjsb_total(detailDataCount);

        //4. 详情数据正式库统计人数（一定是正确的，条件为当前月份）
        List<LinkedHashMap<String, Object>> detailOfficialData = cerDetaildataImportOfficeInfoMapper.countDetailOfficialData(
            time);
        dataScreen.setXqsjsbzsk_total(detailOfficialData.size());

        //5. 内镜检查人数（详情数据正式库里面有内镜报告单的，条件为当前月份）
        long njCount = detailOfficialData
            .parallelStream()
            .filter(map -> map
                .get("nj_report_status")
                .equals(1))
            .count();
        dataScreen.setNjjc_total((int) njCount);

        //6. 胃镜检查人数（全地区的同一月份的总量，条件为当前月份）
        List<LinkedHashMap<String, Object>> gastroscopeData = cerGastroscopeDiagnosisCollectInfoMapper.countGastroscopeData(
            year);
        //处返回胃镜检查总数
        int wjTotal = handleNjReport(gastroscopeData, month);
        dataScreen.setWjjc_total(wjTotal);

        //详情数据正式库-食管癌分布数量
        long sgaCount = handlePieChart("sgbl_code", detailOfficialData);
        dataScreen.setSga_total((int) sgaCount);

        //详情数据正式库-胃癌分布数量
        long waCount = handlePieChart("wbl_code", detailOfficialData);
        dataScreen.setWa_total((int) waCount);

        //详情数据正式库-贲门癌分布数量
        long bmaCount = handlePieChart("bmbl_code", detailOfficialData);
        dataScreen.setBma_total((int) bmaCount);

        //三癌总数-当前月份的数据
        int saTotal = (int) (sgaCount + waCount + bmaCount);
        dataScreen.setSa_total(saTotal);

        // 柱状图json数据
        String histogramData = getHistogramData(initOfficialData,
                                                detailOfficialData,
                                                gastroscopeCountMap);
        dataScreen.setHistogram_json(histogramData);

        //是否删除
        dataScreen.setDeleted(0);
        //数据插入时间
        dataScreen.setInsert_datetime(new Date(System.currentTimeMillis()));

        //设置ext_flag
        dataScreen.setExt_flag("340000|" + areaName);

        XxlJobHelper.log("插入安徽省的数据成功,", LocalDateTime.now());
        return cerDataScreenMapper.insert(dataScreen);
    }

    /**
     * 处理组装大屏数据
     */
    private void handleDataScreenSub(String year, String month) {
        // 获取安徽省下的所有的地市
        PageData pageData = new PageData();
        pageData.put("parentRegionCode", "340000");
        List<LinkedHashMap<String, Object>> allCities = zjcodeSysRegionMapper.getAllCities(pageData);
        Map<String, String> gastroscopeCountMap = new HashMap<>();
        // 取出每个城市的胃镜信息
        allCities
            .stream()
            .forEach(each -> {
                // 城市名称
                String cityName = (String) each.get("name");
                // 城市编码
                String cityid = (String) each.get("id");
                // 胃镜检查人数（全地区的同一月份的总量，条件为当前月份）
                List<LinkedHashMap<String, Object>> gastroscopeData = cerGastroscopeDiagnosisCollectInfoMapper.countGastroscopeDataT2(
                    year,
                    cityName);
                // 处返回胃镜检查总数
                int wjTotal = handleNjReport(gastroscopeData, month);
                gastroscopeCountMap.put(cityName + "|" + cityid, String.valueOf(wjTotal));
            });

        allCities
            .stream()
            .forEach(each -> {
                // 城市名称
                String cityName = (String) each.get("name");
                // 城市编码
                String cityid = (String) each.get("id");
                log.info("name:{},id:{}", cityName, cityid);

                //新建数据大屏实体
                CerDataScreen dataScreen = new CerDataScreen();
                //主键
                dataScreen.setId(get32UUID());
                //当前年份
                dataScreen.setYear(Integer.valueOf(year));
                //当前月份
                dataScreen.setMonth(Integer.valueOf(month));

                // 获取当前月份，开始获取数据
                Date time = Utils.getFirstDay(1);

                //1. 初始数据上报统计人数（不管有没有错误，条件为当前月份）
                int initDataCount = cerSysteminitImportInfoMapper.countInitDataT2(time, cityid);
                dataScreen.setCssjsb_total(initDataCount);

                //2. 初始数据正式库统计人数（一定是正确的，条件为当前月份）
                List<LinkedHashMap<String, Object>> initOfficialData = cerSysteminitImportOfficialInfoMapper.initOfficialDataT2(
                    time,
                    cityid);
                dataScreen.setCssjshzsk_total(initOfficialData.size());

                //3. 详情数据上报统计人数（不管有没有错误的，条件为当前月份）
                int detailDataCount = cerDetaildataImportInfoMapper.countDetailDataT2(time, cityid);
                dataScreen.setXqsjsb_total(detailDataCount);

                //4. 详情数据正式库统计人数（一定是正确的，条件为当前月份）
                List<LinkedHashMap<String, Object>> detailOfficialData = cerDetaildataImportOfficeInfoMapper.countDetailOfficialDataT2(
                    time,
                    cityid);
                dataScreen.setXqsjsbzsk_total(detailOfficialData.size());

                //5. 内镜检查人数（详情数据正式库里面有内镜报告单的，条件为当前月份）
                long njCount = detailOfficialData
                    .parallelStream()
                    .filter(map -> map
                        .get("nj_report_status")
                        .equals(1))
                    .count();
                dataScreen.setNjjc_total((int) njCount);

                //6. 胃镜检查人数（全地区的同一月份的总量，条件为当前月份）
                //List<LinkedHashMap<String, Object>> gastroscopeData = cerGastroscopeDiagnosisCollectInfoMapper.countGastroscopeDataT2(
                //    year,
                //    cityName);
                ////处返回胃镜检查总数
                //int wjTotal = handleNjReport(gastroscopeData, month);
                //dataScreen.setWjjc_total(wjTotal);
                String wjTotal = gastroscopeCountMap.get(cityName + "|" + cityid);
                dataScreen.setWjjc_total(Integer.parseInt(wjTotal));

                //详情数据正式库-食管癌分布数量
                long sgaCount = handlePieChart("sgbl_code", detailOfficialData);
                dataScreen.setSga_total((int) sgaCount);

                //详情数据正式库-胃癌分布数量
                long waCount = handlePieChart("wbl_code", detailOfficialData);
                dataScreen.setWa_total((int) waCount);

                //详情数据正式库-贲门癌分布数量
                long bmaCount = handlePieChart("bmbl_code", detailOfficialData);
                dataScreen.setBma_total((int) bmaCount);

                //三癌总数-当前月份的数据
                int saTotal = (int) (sgaCount + waCount + bmaCount);
                dataScreen.setSa_total(saTotal);

                //柱状图json数据
                String histogramData = getHistogramData(initOfficialData,
                                                        detailOfficialData,
                                                        gastroscopeCountMap);
                dataScreen.setHistogram_json(histogramData);

                //是否删除
                dataScreen.setDeleted(0);
                //数据插入时间
                dataScreen.setInsert_datetime(new Date(System.currentTimeMillis()));

                //放入extflag
                dataScreen.setExt_flag(cityid + "|" + cityName);
                cerDataScreenMapper.insert(dataScreen);

                log.info("插入{}的数据成功", cityName);

                XxlJobHelper.log("插入{}的数据成功,", cityName, LocalDateTime.now());
            });
    }

    /**
     * 获取安徽省下各个城市,在指定年月情况下的,每月上报胃镜的个数
     *
     * @param year
     * @param month
     * @return
     */
    private Map<String, String> getGastroscopeCountMap(String year, String month) {
        PageData pageData = new PageData();
        pageData.put("parentRegionCode", "340000");
        List<LinkedHashMap<String, Object>> allCities = zjcodeSysRegionMapper.getAllCities(pageData);
        Map<String, String> gastroscopeCountMap = new HashMap<>();
        // 取出每个城市的胃镜信息
        allCities
            .stream()
            .forEach(each -> {
                // 城市名称
                String cityName = (String) each.get("name");
                // 城市编码
                String cityid = (String) each.get("id");
                // 胃镜检查人数（全地区的同一月份的总量，条件为当前月份）
                List<LinkedHashMap<String, Object>> gastroscopeData = cerGastroscopeDiagnosisCollectInfoMapper.countGastroscopeDataT2(
                    year,
                    cityName);
                // 处返回胃镜检查总数
                int wjTotal = handleNjReport(gastroscopeData, month);
                gastroscopeCountMap.put(cityName + "|" + cityid, String.valueOf(wjTotal));
            });
        return gastroscopeCountMap;
    }


    /**
     * 组装柱状图所需json数据
     *
     * @param initOfficialData   初始数据正式库统计人数（一定是正确的，条件为当前月份）
     * @param detailOfficialData 详情数据正式库统计人数（一定是正确的，条件为当前月份）
     * @return 饼图所需json数据
     */
    private String getHistogramData(List<LinkedHashMap<String, Object>> initOfficialData,
                                    List<LinkedHashMap<String, Object>> detailOfficialData) {
        //新建前端数据集合
        List<Histogram> list = new ArrayList<>();

        //3.所有地区数据
        List<LinkedHashMap<String, Object>> allAreaData = zjcodeSysRegionMapper.allAreaData();

        allAreaData
            .stream()
            .forEach(areaData -> {
                //柱状图数据实体
                Histogram histogram = new Histogram();
                //地区名称
                String regionName = String.valueOf(areaData.get("region_name"));
                //地区代码
                String regionCode = String.valueOf(areaData.get("region_code"));

                //初始数据正式库统计人数
                long initOfficialDataCount = initOfficialData
                    .parallelStream()
                    .filter(initData -> initData
                        .get("city_id")
                        .equals(regionCode))
                    .count();

                //详情数据正式库统计人数
                long detailOfficialDataCount = detailOfficialData
                    .parallelStream()
                    .filter(detailData -> detailData
                        .get("city_id")
                        .equals(regionCode))
                    .count();

                //组合数据
                histogram.setId(get32UUID());
                histogram.setRegion_name(regionName);
                histogram.setRegion_code(regionCode);
                histogram.setInit_official_count((int) initOfficialDataCount);
                histogram.setDetail_official_count((int) detailOfficialDataCount);
                list.add(histogram);
            });
        return JSON.toJSONString(list);
    }

    private String getHistogramData(List<LinkedHashMap<String, Object>> initOfficialData,
                                    List<LinkedHashMap<String, Object>> detailOfficialData,
                                    Map<String, String> gastroscopeCountMap) {
        //新建前端数据集合
        List<Histogram> list = new ArrayList<>();

        //3.所有地区数据
        List<LinkedHashMap<String, Object>> allAreaData = zjcodeSysRegionMapper.allAreaData();

        allAreaData
            .stream()
            .forEach(areaData -> {
                //柱状图数据实体
                Histogram histogram = new Histogram();
                //地区名称
                String regionName = String.valueOf(areaData.get("region_name"));
                //地区代码
                String regionCode = String.valueOf(areaData.get("region_code"));

                //初始数据正式库统计人数
                long initOfficialDataCount = initOfficialData
                    .parallelStream()
                    .filter(initData -> initData
                        .get("city_id")
                        .equals(regionCode))
                    .count();

                //详情数据正式库统计人数
                long detailOfficialDataCount = detailOfficialData
                    .parallelStream()
                    .filter(detailData -> detailData
                        .get("city_id")
                        .equals(regionCode))
                    .count();

                String wjTotalStr = gastroscopeCountMap.get(regionName + "|" + regionCode);

                //组合数据
                histogram.setId(get32UUID());
                histogram.setRegion_name(regionName);
                histogram.setRegion_code(regionCode);
                histogram.setGastroscope_count(Integer.parseInt(wjTotalStr));
                histogram.setInit_official_count((int) initOfficialDataCount);
                histogram.setDetail_official_count((int) detailOfficialDataCount);
                list.add(histogram);
            });
        return JSON.toJSONString(list);
    }

    /**
     * 计算胃镜检查人数
     *
     * @param gastroscopeData 胃镜检查数据
     * @param month           当前月份
     * @return int 胃镜检查总数
     */
    private int handleNjReport(List<LinkedHashMap<String, Object>> gastroscopeData, String month) {
        //字段map
        Map<String, Object> map = new HashMap<>();
        map.put("1", "jan_count");
        map.put("2", "feb_count");
        map.put("3", "mar_count");
        map.put("4", "apr_count");
        map.put("5", "may_count");
        map.put("6", "jun_count");
        map.put("7", "jul_count");
        map.put("8", "aug_count");
        map.put("9", "sept_count");
        map.put("10", "oct_count");
        map.put("11", "nov_count");
        map.put("12", "dec_count");

        //总数
        int total = 0;
        for (LinkedHashMap<String, Object> gastroscopeDatum : gastroscopeData) {
            //根据当前月份get到数据字段
            String column = map
                .get(String.valueOf(month))
                .toString();
            //获取到数据
            Object obj = gastroscopeDatum.get(column);
            total += Integer.parseInt(obj.toString());
        }
        return total;
    }

    /**
     * 计算饼图数据
     *
     * @param detailOfficialData 详情数据正式库数据
     * @return long 数量
     */
    private long handlePieChart(String key,
                                List<LinkedHashMap<String, Object>> detailOfficialData) {
        return detailOfficialData
            .parallelStream()
            .filter(each -> Objects.nonNull(each.get(key)))
            .count();
    }
}
